<?php
/**
 * Created by PhpStorm.
 * User: wstianxia
 * @copyright: ©2024 深圳网商天下科技
 * @link: https://www.netbcloud.com
 */

namespace app\forms\common\attachment;

use app\models\AttachmentStorage;
use app\models\Model;
use app\models\User;

/**
 * Class CommonAttachment
 * @package app\forms\common\attachment
 * @property User $user
 */
class CommonAttachment extends Model
{
    public $user;
    protected $user_id;

    public function init()
    {
        parent::init(); // TODO: Change the autogenerated stub
        $this->setUserId($this->user ? $this->user->id : $this->user_id);
    }

    public function setUserId($userId)
    {
        $this->user_id = $userId;
    }

    public static function getCommon($user = null)
    {
        return new self([
            'user' => $user
        ]);
    }

    public function getStorage()
    {
        return [
            AttachmentStorage::STORAGE_TYPE_LOCAL => '本地服务器',
            AttachmentStorage::STORAGE_TYPE_ALIOSS => '阿里云OSS',
            AttachmentStorage::STORAGE_TYPE_TXCOS => '腾讯云COS',
            AttachmentStorage::STORAGE_TYPE_QINIU => '七牛云存储',
            AttachmentStorage::STORAGE_TYPE_TOS => '火山云TOS',
        ];
    }

    /**
     * @param $data
     * @return bool
     * @throws \Exception
     */
    public function attachmentCreateStorage($data)
    {
        $condition = [
            'type' => $data['type'],
            'user_id' => $this->user_id
        ];
        if ($data['id']) {
            $condition['id'] = $data['id'];
        }
        $storage = AttachmentStorage::findOne($condition);
        if (!$data['id'] && $storage) {
            throw new \Exception('该存储位置已配置过，请选择其它存储位置。');
        } elseif ($data['id'] && !$storage) {
            throw new \Exception('配置不存在，请刷新页面重新加载内容。');
        } elseif (!$data['id']) {
            $storage = new AttachmentStorage();
        }

        if (isset($data['config']) && is_array($data['config'])) {
            foreach ($data['config'] as &$item) {
                $item = trim($item);
            }
            unset($item);
        }

        $storage->user_id = $this->user_id;
        $storage->type = $data['type'];
        $storage->config = isset($data['config']) ? \Yii::$app->serializer->encode($data['config']) : '""';
        if ($storage->isNewRecord) {
            $storage->status = 0;
        }
        if ($storage->save()) {
            return true;
        } else {
            throw new \Exception($this->getErrorMsg($storage));
        }
    }

    public function attachmentEnableStorage($id)
    {
        $condition = ['user_id' => $this->user_id];
        AttachmentStorage::updateAll(['status' => 0], $condition);
        $condition['id'] = $id;
        AttachmentStorage::updateAll(['status' => 1], $condition);
        return true;
    }

    /**
     * @return array|\yii\db\ActiveRecord[]
     * @throws \Exception
     * 获取指定账号指定商城的存储设置列表
     */
    public function getAttachmentList()
    {
        $auth = $this->getStorageAuth();
        if (!is_array($auth)) {
            return [];
        }
        $list = AttachmentStorage::find()
            ->where(['type' => $auth, 'user_id' => $this->user_id])
            ->orderBy('id DESC')->asArray()->all();
        foreach ($list as &$item) {
            $item['config'] = \Yii::$app->serializer->decode($item['config']);
        }
        return $list;
    }

    /**
     * @return AttachmentStorage|null
     * @throws \Exception
     * 获取可使用的存储设置
     */
    public function getAttachment()
    {
        $storageAuth = $this->getStorageAuth();
        $attachment = AttachmentStorage::findOne([
            'user_id' => $this->user_id, 'status' => 1, 'type' => $storageAuth
        ]);
        if (!$attachment && in_array(AttachmentStorage::STORAGE_TYPE_LOCAL, $storageAuth)) {
            $attachment = new AttachmentStorage();
            $attachment->type = AttachmentStorage::STORAGE_TYPE_LOCAL;
            $attachment->user_id = 0;
            $attachment->config = "";
            $attachment->id = 0;
            $attachment->status = 1;
        }
        if(!$attachment) {
            throw new \Exception('请先配置上传设置');
        }
        return $attachment;
    }

    /**
     * @return array|mixed
     * @throws \Exception
     * 获取指定账户上传权限
     */
    public function getStorageAuth()
    {
        return $this->getDefaultAuth();
    }

    public function getDefaultAuth()
    {
        return [1, 2, 3, 4, 5];
    }

    public function getStorageType()
    {
        $auth = $this->getStorageAuth();
        if (!is_array($auth)) {
            $auth = [];
        }
        $storage = $this->getStorage();
        $storageType = [];
        foreach ($auth as $item) {
            $storageType[$item] = $storage[$item];
        }
        return $storageType;
    }
}
